﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Utilities;

namespace ManageTicket.Ticket
{
    public partial class frmInvoiceSeries : frmBase
    {
        #region Contructor
        public frmInvoiceSeries()
        {
            InitializeComponent();
        }
        #endregion

        #region Variable
        ManageTicket.Library.Control.ExecuteControl exeCtrl;

        //permission
        bool bAdd = false;
        bool bEdit = false;
        bool bDelete = false;
        bool bCancel = false;
        bool bSave = false;
        bool bFunction = false;
        bool bView = false;
        bool bFind = false;
        bool bExport = false;
        bool bSendmail = false;
        bool bPrint = false;

        clsMethod4All objMethod = new clsMethod4All();
        ManageTicket.Library.Common.CommonFunction clsCommonFunc = new ManageTicket.Library.Common.CommonFunction();

        Business.CodeType boCodeType = new Business.CodeType();
        Business.Employee boEmployee = new Business.Employee();
        Business.Voucher boVoucher = new Business.Voucher();
        Business.Invoice boInvoice = new Business.Invoice();

        ArrayList arrType;
        ArrayList arrCurrency;
        ArrayList arrPayForm;
        ArrayList arrBank;
        ArrayList arrEmployee = new ArrayList();
        ArrayList arrReceivers = new ArrayList();
        ArrayList arrResult = new ArrayList();
        #endregion

        #region Event
        private void frmInvoiceSeries_Load(object sender, EventArgs e)
        {
            //execute control
            exeCtrl = new ManageTicket.Library.Control.ExecuteControl();
            exeCtrl.Dock = DockStyle.Fill;
            exeCtrl.lblDescription.Text = "Cập nhật hóa đơn hàng loạt." + Environment.NewLine + "Chú ý: Các dòng có số tiền thanh toán bằng 0 sẽ không được cập nhật.";
            pnlExe.Controls.Add(exeCtrl);

            //permission
            clsCommonFunc.GetPermission(ref bAdd, ref bEdit, ref bDelete, ref bCancel, ref bSave, ref bFunction, ref bView, ref bFind, ref bExport, ref bSendmail, ref bPrint, frmMain.CurrentUser.UserId, this.Name);

            LoadStatusOnce();
            LoadStatus(false, true);

            arrType = boCodeType.GetListCodeTypeByGroup("VSTATUS", "VSTATUS_1");
            arrCurrency = boCodeType.GetListCodeTypeByGroup("CUR");
            arrPayForm = boCodeType.GetListCodeTypeByGroup("PF");
            arrBank = boCodeType.GetListCodeTypeByGroup("BANK");
            ArrayList arrEmployee_;
            arrEmployee_ = boEmployee.List();
            ManageTicket.Library.Common.ObjectInfo oInfo;
            foreach (DataObjects.Employee oEmp in arrEmployee_)
            {
                oInfo = new ManageTicket.Library.Common.ObjectInfo();
                oInfo.Code = oEmp.EmployeeId;
                oInfo.Name = oEmp.LastName + " " + oEmp.FirstName;
                arrEmployee.Add(oInfo);
            }
            foreach (DataObjects.Employee oEmp in arrEmployee_)
            {
                oInfo = new ManageTicket.Library.Common.ObjectInfo();
                oInfo.Code = oEmp.EmployeeId;
                oInfo.Name = oEmp.LastName + " " + oEmp.FirstName;
                arrReceivers.Add(oInfo);
            }
        }
        #endregion

        #region Execute
        public override void Find()
        {
            frmFindTicket frmFind = new frmFindTicket();
            frmFind.ShowDialog();
            arrResult = frmFind.arrResult;

            FillData();
        }

        public override void Save()
        {
            int result = 0;
            for (int i = 0; i < dtgvDetail.Rows.Count; i++)
            {
                if (dtgvDetail.Rows[i].Cells["colSelect"].Value.ToString().ToLower() == "true")
                {
                    if (dtgvDetail.Rows[i].Cells["colBalance"].Value.ToString().ToLower() != "0")
                    {
                        try
                        {
                            DataObjects.Invoice oInvoice = new DataObjects.Invoice();
                            oInvoice.InvoiceNo = DateTime.Now.ToString("yyMMdd") + clsCommonFunc.RuleNumber5(boInvoice.GetMaxID(DateTime.Now.ToString("yyMMdd")) + 1);
                            oInvoice.VoucherNo = dtgvDetail.Rows[i].Cells["colVoucherNo"].Value.ToString();
                            oInvoice.DateOfInvoice = DateTime.Now;
                            oInvoice.KindOfVoucher = dtgvDetail.Rows[i].Cells["colKindOfVoucher"].Value.ToString();
                            oInvoice.KindOfInvoice = dtgvDetail.Rows[i].Cells["colKindOfInvoice"].Value.ToString();
                            if (dtgvDetail.Rows[i].Cells["colCurrencyTT"].Value.ToString() == "CUR_1")
                            {
                                if (double.Parse(dtgvDetail.Rows[i].Cells["colQuydoi_VND"].Value.ToString()) > 0)
                                {
                                    oInvoice.Money = dtgvDetail.Rows[i].Cells["colQuydoi_VND"].Value.ToString() != "" ? double.Parse(dtgvDetail.Rows[i].Cells["colQuydoi_VND"].Value.ToString()) : 0;
                                }
                                else if (double.Parse(dtgvDetail.Rows[i].Cells["colDept_VND"].Value.ToString()) > 0)
                                {
                                    oInvoice.Money = dtgvDetail.Rows[i].Cells["colDept_VND"].Value.ToString() != "" ? double.Parse(dtgvDetail.Rows[i].Cells["colDept_VND"].Value.ToString()) : 0;
                                }
                            }
                            else
                            {
                                oInvoice.Money = dtgvDetail.Rows[i].Cells["colDept_USD"].Value.ToString() != "" ? double.Parse(dtgvDetail.Rows[i].Cells["colDept_USD"].Value.ToString()) : 0;
                            }

                            oInvoice.Currency = dtgvDetail.Rows[i].Cells["colCurrencyTT"].Value.ToString();
                            oInvoice.Exchange = dtgvDetail.Rows[i].Cells["colExchange"].Value.ToString() != "" ? double.Parse(dtgvDetail.Rows[i].Cells["colExchange"].Value.ToString()) : 0;
                            oInvoice.PaymentForm = dtgvDetail.Rows[i].Cells["colPaymentForm"].Value.ToString();
                            if (oInvoice.PaymentForm != "PF_1")
                                oInvoice.Bank = dtgvDetail.Rows[i].Cells["colBank"].Value.ToString();
                            oInvoice.Cashier = dtgvDetail.Rows[i].Cells["colCashier"].Value.ToString();
                            oInvoice.Receiver = dtgvDetail.Rows[i].Cells["colReceiver"].Value.ToString();
                            oInvoice.Remark = dtgvDetail.Rows[i].Cells["colRemark"].Value.ToString();


                            //insert
                            if (CheckIsExist(oInvoice.InvoiceNo))
                            {

                                return;
                            }
                            boInvoice.Insert(oInvoice);
                            InsertVoucherHistory(oInvoice);
                            result++;
                        }
                        catch (Exception ex)
                        {

                            //throw;
                        }


                    }
                }
            }
            if (result > 0)
                MessageBox.Show("Cập nhật thành công " + result.ToString() + " hóa đơn.", "Aquarius", MessageBoxButtons.OK, MessageBoxIcon.Information);
            else
                MessageBox.Show("Không có hóa đơn nào được cập nhật.", "Aquarius Error", MessageBoxButtons.OK, MessageBoxIcon.Information);

            FillData();
        }
        #endregion

        #region Method
        private void LoadStatusOnce()
        {
            exeCtrl.btnAdd.Enabled = false;
            exeCtrl.btnEdit.Enabled = false;
            exeCtrl.btnDelete.Enabled = false;
            exeCtrl.btnCancel.Enabled = false;
            exeCtrl.btnFunction.Enabled = false;
            exeCtrl.btnView.Enabled = false;
            exeCtrl.btnExport.Enabled = false;
            exeCtrl.btnSendmail.Enabled = false;
            exeCtrl.btnPrint.Enabled = false;

            exeCtrl.btnAdd.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnEdit.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnDelete.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnCancel.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnFunction.BackColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnView.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnExport.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnSendmail.ButtonColor = Color.FromArgb(171, 171, 171);
            exeCtrl.btnPrint.ButtonColor = Color.FromArgb(171, 171, 171);

            exeCtrl.btnAdd.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnEdit.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnDelete.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnCancel.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnFunction.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnView.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnExport.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnSendmail.ForeColor = Color.FromArgb(241, 244, 251);
            exeCtrl.btnPrint.ForeColor = Color.FromArgb(241, 244, 251);
        }

        private void LoadStatus(bool blSave, bool blFind)
        {
            exeCtrl.btnSave.Enabled = blSave & bSave;
            exeCtrl.btnFind.Enabled = blFind & bFind;

            exeCtrl.btnSave.ButtonColor = exeCtrl.btnSave.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);
            exeCtrl.btnFind.ButtonColor = exeCtrl.btnFind.Enabled ? Color.FromArgb(0, 163, 211) : Color.FromArgb(171, 171, 171);

            exeCtrl.btnSave.ForeColor = exeCtrl.btnSave.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
            exeCtrl.btnFind.ForeColor = exeCtrl.btnFind.Enabled ? Color.FromArgb(0, 0, 0) : Color.FromArgb(241, 244, 251);
        }

        private void AddRowInGridView(DataObjects.Voucher oVou, string providername)
        {
            try
            {
                System.Windows.Forms.DataGridViewRow dgvRow = new System.Windows.Forms.DataGridViewRow();
                System.Windows.Forms.DataGridViewCell dgvCell;
                double muaUSD = 0;
                double datraUSD = 0;
                double noUSD = 0;
                double tygia = 0;
                double quydoiVND = 0;
                double muaVND = 0;
                double datraVND = 0;
                double noVND = 0;
                double balance = 0;

                if (oVou.BuyCurrency == "CUR_1") //VND
                {
                    muaVND = oVou.BuySum;
                }
                else if (oVou.BuyCurrency == "CUR_2") //USD
                {
                    muaUSD = oVou.BuySum;
                }

                datraVND = TinhSoTienDaTra(oVou.VoucherNo, "CUR_1");
                noVND = muaVND - datraVND;

                datraUSD = TinhSoTienDaTra(oVou.VoucherNo, "CUR_2");
                noUSD = muaUSD - datraUSD;
                tygia = oVou.BuyExchange;
                quydoiVND = noUSD * tygia;

                balance = quydoiVND + noVND;


                //check
                dgvCell = new DataGridViewCheckBoxCell();
                dgvCell.Value = balance > 0;
                dgvRow.Cells.Add(dgvCell);
                dgvCell.ReadOnly = balance <= 0;

                //voucher
                dgvCell = new DataGridViewTextBoxCell();
                dgvCell.Value = oVou.VoucherNo;
                dgvRow.Cells.Add(dgvCell);
                dgvCell.ReadOnly = true;

                //date of voucher
                dgvCell = new DataGridViewTextBoxCell();
                dgvCell.Value = oVou.DateOfVoucher.Value.ToString("dd/MM/yyyy");
                dgvRow.Cells.Add(dgvCell);
                dgvCell.ReadOnly = true;

                //provider id
                dgvCell = new DataGridViewTextBoxCell();
                dgvCell.Value = oVou.ProviderId;
                dgvRow.Cells.Add(dgvCell);
                dgvCell.ReadOnly = true;

                //provider name
                dgvCell = new DataGridViewTextBoxCell();
                dgvCell.Value = providername;
                dgvRow.Cells.Add(dgvCell);
                dgvCell.ReadOnly = true;

                //mua USD 
                dgvCell = new DataGridViewTextBoxCell();
                dgvCell.Value = objMethod.FormatCurency(muaUSD.ToString());
                dgvRow.Cells.Add(dgvCell);
                dgvCell.ReadOnly = true;

                //da tra USD
                dgvCell = new DataGridViewTextBoxCell();
                dgvCell.Value = objMethod.FormatCurency(datraUSD.ToString());
                dgvRow.Cells.Add(dgvCell);
                dgvCell.ReadOnly = true;

                //no USD
                dgvCell = new DataGridViewTextBoxCell();
                dgvCell.Value = objMethod.FormatCurency(noUSD.ToString());
                dgvRow.Cells.Add(dgvCell);
                dgvCell.ReadOnly = true;

                //ty gia
                dgvCell = new DataGridViewTextBoxCell();
                dgvCell.Value = objMethod.FormatCurency(tygia.ToString());
                dgvRow.Cells.Add(dgvCell);
                dgvCell.ReadOnly = true;

                //quy doi vnd
                dgvCell = new DataGridViewTextBoxCell();
                dgvCell.Value = objMethod.FormatCurency(quydoiVND.ToString());
                dgvRow.Cells.Add(dgvCell);
                dgvCell.ReadOnly = true;

                //mua VND
                dgvCell = new DataGridViewTextBoxCell();
                dgvCell.Value = objMethod.FormatCurency(muaVND.ToString());
                dgvRow.Cells.Add(dgvCell);
                dgvCell.ReadOnly = true;

                //da tra VND
                dgvCell = new DataGridViewTextBoxCell();
                dgvCell.Value = objMethod.FormatCurency(datraVND.ToString());
                dgvRow.Cells.Add(dgvCell);
                dgvCell.ReadOnly = true;

                //no VND
                dgvCell = new DataGridViewTextBoxCell();
                dgvCell.Value = objMethod.FormatCurency(noVND.ToString());
                dgvRow.Cells.Add(dgvCell);
                dgvCell.ReadOnly = true;

                //balance
                dgvCell = new DataGridViewTextBoxCell();
                dgvCell.Value = objMethod.FormatCurency(balance.ToString());
                dgvRow.Cells.Add(dgvCell);
                dgvCell.ReadOnly = true;

                //loai
                DataGridViewComboBoxCell dgvCellType = new DataGridViewComboBoxCell();
                dgvCellType.DataSource = arrType;
                dgvCellType.DisplayMember = "CodeTypeName";
                dgvCellType.ValueMember = "CodeTypeId";
                dgvCellType.Value = "VSTATUS_2";
                dgvRow.Cells.Add(dgvCellType);
                dgvCellType.ReadOnly = true;

                //thu/chi
                DataGridViewComboBoxCell dgvCellKOI = new DataGridViewComboBoxCell();
                dgvCellKOI.Items.Add("Thu");
                dgvCellKOI.Items.Add("Chi");
                dgvCellKOI.Value = dgvCellKOI.Items[1];
                dgvRow.Cells.Add(dgvCellKOI);
                dgvCellKOI.ReadOnly = true;

                //hinh thuc thanh toan
                DataGridViewComboBoxCell dgvCellPayForm = new DataGridViewComboBoxCell();
                dgvCellPayForm.DataSource = arrPayForm;
                dgvCellPayForm.DisplayMember = "CodeTypeName";
                dgvCellPayForm.ValueMember = "CodeTypeId";
                dgvCellPayForm.Value = "PF_1";
                dgvRow.Cells.Add(dgvCellPayForm);

                //ngan hang
                DataGridViewComboBoxCell dgvCellBank = new DataGridViewComboBoxCell();
                dgvCellBank.DataSource = arrBank;
                dgvCellBank.DisplayMember = "CodeTypeName";
                dgvCellBank.ValueMember = "CodeTypeId";
                //dgvCellBank.Value = "";
                dgvRow.Cells.Add(dgvCellBank);

                //nguoi lap
                DataGridViewComboBoxCell dgvCellCashier = new DataGridViewComboBoxCell();
                dgvCellCashier.DataSource = arrEmployee;
                dgvCellCashier.DisplayMember = "Name";
                dgvCellCashier.ValueMember = "Code";
                dgvCellCashier.Value = frmMain.CurrentUser.EmployeeId;
                dgvRow.Cells.Add(dgvCellCashier);

                //nguoi nhan
                DataGridViewComboBoxCell dgvCellReceiver = new DataGridViewComboBoxCell();
                dgvCellReceiver.DataSource = arrReceivers;
                dgvCellReceiver.DisplayMember = "Name";
                dgvCellReceiver.ValueMember = "Code";
                dgvCellReceiver.Value = frmMain.CurrentUser.EmployeeId;
                dgvRow.Cells.Add(dgvCellReceiver);

                //ghi chu
                dgvCell = new DataGridViewTextBoxCell();
                dgvCell.Value = "";
                dgvRow.Cells.Add(dgvCell);
                dgvCell.ReadOnly = false;

                //loai tien thanh toan
                DataGridViewComboBoxCell dgvCellCurrencyTT = new DataGridViewComboBoxCell();
                dgvCellCurrencyTT.DataSource = arrCurrency;
                dgvCellCurrencyTT.DisplayMember = "CodeTypeName";
                dgvCellCurrencyTT.ValueMember = "CodeTypeId";
                dgvCellCurrencyTT.Value = oVou.BuyCurrency;
                dgvRow.Cells.Add(dgvCellCurrencyTT);
                //dgvCellCurrencyTT.ReadOnly = true;

                //add row to gridview
                dtgvDetail.Rows.Add(dgvRow);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private double TinhSoTienDaTra(string voucher_no, string type)
        {
            //type : loai tien da tra
            //value :   CUR_1 --> VND
            //          CUR_2 --> USD
            try
            {
                double money = 0;

                ArrayList arr = boInvoice.GetListByVoucherNo(voucher_no);
                foreach (DataObjects.Invoice oInv in arr)
                {
                    if (oInv.KindOfVoucher == "VSTATUS_2" && oInv.Currency == type)
                        money += oInv.Money;
                }
                return money;
            }
            catch (Exception ex)
            {
                return 0;
                throw ex;
            }
        }

        private bool CheckIsExist(string invoice_no)
        {
            DataObjects.Invoice oInvoice = boInvoice.GetObjectByPK(invoice_no);
            if (oInvoice != null)
            {
                return true;
            }
            return false;
        }

        private void InsertVoucherHistory(DataObjects.Invoice oInvoice)
        {
            Business.VoucherHistory boVoucherHistory = new Business.VoucherHistory();
            //insert
            DataObjects.VoucherHistory oVouHis = new DataObjects.VoucherHistory();
            oVouHis.VoucherNo = oInvoice.VoucherNo;
            oVouHis.InvoiceNo = oInvoice.InvoiceNo;
            oVouHis.DateCreate = oInvoice.DateOfInvoice;
            oVouHis.Status = oInvoice.KindOfVoucher;
            oVouHis.Remark = oInvoice.Remark;
            oVouHis.UserId = frmMain.CurrentUser.UserId;
            oVouHis.DateInput = DateTime.Now;
            if (oInvoice.Currency.ToUpper() == "CUR_1")
            {
                if (oInvoice.KindOfInvoice.ToUpper() == "THU")
                {
                    oVouHis.IncomingVnd = oInvoice.Money;
                }
                else if (oInvoice.KindOfInvoice.ToUpper() == "CHI")
                {
                    oVouHis.OutgoingVnd = oInvoice.Money;
                }
            }
            else if (oInvoice.Currency.ToUpper() == "CUR_2")
            {
                if (oInvoice.KindOfInvoice.ToUpper() == "THU")
                {
                    oVouHis.IncomingUsd = oInvoice.Money;
                }
                else if (oInvoice.KindOfInvoice.ToUpper() == "CHI")
                {
                    oVouHis.OutgoingUsd = oInvoice.Money;
                }
            }

            boVoucherHistory.Insert(oVouHis);
        }

        private void FillData()
        {
            dtgvDetail.Rows.Clear();

            //datatable
            //DataTable dt = objMethod.CreateDataTable("Data", new string[] { "VOUCHER_NO", "DATE_OF_VOUCHER", "PROVIDER_ID", "PROVIDER_NAME", "SOTIENMUA_USD", "SOTIENDATRA_USD", "SOTIENMUA_VND", "SOTIENDATRA_VND" });
            //DataRow row;
            Business.Provider boProvider = new Business.Provider();
            DataObjects.Provider oPro;
            DataObjects.Voucher oVou;

            foreach (DataObjects.Voucher oVou_ in arrResult)
            {
                oVou = boVoucher.GetObjectByPK(oVou_.VoucherNo);
                oPro = boProvider.GetObjectByPK(oVou.ProviderId);
                AddRowInGridView(oVou, oPro.ProviderName);
            }
            CalcTotalVND();
        }

        private void CalcTotalVND()
        {
            if (dtgvDetail.RowCount > 0)
            {
                LoadStatus(true, true);
                double SoTienThanhToanVND = 0;
                double vnd = 0;
                double usd = 0;

                for (int i = 0; i < dtgvDetail.Rows.Count; i++)
                {
                    try
                    {
                        usd += double.Parse(dtgvDetail.Rows[i].Cells["colDept_USD"].Value.ToString());
                        vnd += double.Parse(dtgvDetail.Rows[i].Cells["colDept_VND"].Value.ToString());
                        SoTienThanhToanVND += double.Parse(dtgvDetail.Rows[i].Cells["colBalance"].Value.ToString());
                    }
                    catch { }


                }
                txtTotal.Text = objMethod.FormatCurency(SoTienThanhToanVND.ToString());
                txtSumVND.Text = objMethod.FormatCurency(vnd.ToString());
                txtSumUSD.Text = objMethod.FormatCurency(usd.ToString());
            }
            else
            {
                LoadStatus(false, true);
                txtTotal.Text = "0";
            }
        }
        #endregion 
        
    }
}
